package com.jerry.mingxing.ui.store;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jerry.mingxing.R;
import com.jerry.mingxing.bean.ShowBean;
import com.jerry.mingxing.bean.StoreBean;
import com.jerry.mingxing.bean.StoreHeadBean;
import com.jerry.mingxing.config.UrlConfig;

import com.jerry.mingxing.ui.detail.DetailActivity;
import com.jerry.mingxing.widget.MyContentView;
import com.jerry.mingxing.widget.MyGridView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * Created by Administrator on 2016/8/29.
 */
public class StoreFragment extends Fragment implements StoreContentContract.View,MyContentView.MyContentViewInter {
    @Bind(R.id.storefragment_viewpager)
    ViewPager storefragmentViewpager;


    //自定义view

    //延迟时间
    private final static int TIME = 3500;
    @Bind(R.id.storefragment_mycontentview_korea)
    MyContentView storefragmentMycontentviewKorea;
    @Bind(R.id.storefragment_mycontentview_usa)
    MyContentView storefragmentMycontentviewUsa;
    @Bind(R.id.storefragment_mycontentview_chinese)
    MyContentView storefragmentMycontentviewChinese;
    @Bind(R.id.storefragment_mycontentview_beauty)
    MyContentView storefragmentMycontentviewBeauty;
    @Bind(R.id.storefragment_tablayout)
    TabLayout storefragmentTablayout;
    @Bind(R.id.storefragment_mgv)
    MyGridView storefragmentMgv;
    private View view;
    private StoreAdvertisementAdapter storeHeadAdapter;

    private ShowAdapter showAdapter;





    private Activity activity;
    private List<StoreHeadBean.DataBean.ItemsBean> listHead = new ArrayList<>();
    private List<ShowBean.DataBean.ItemsBean> totallsit=new ArrayList<>();
    //persenter
    private StoreContentPresenter storeContentPresenter;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int type = msg.what;
            switch (type) {
                case 0:
                    //跟据handler发过来的消息去获得当前的页面,然后默认+1页播放
                    int currentItem = storefragmentViewpager.getCurrentItem();
                    storefragmentViewpager.setCurrentItem(++currentItem);
                    break;

            }
        }
    };
    private String[] tabTitlie;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = getActivity();
        showAdapter=new ShowAdapter(totallsit,activity);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.storefragment, container, false);
        ButterKnife.bind(this, view);

        setAdapter();
        loadData();

        return view;
    }


    private void loadData() {

        tabTitlie = getResources().getStringArray(R.array.tablayout);
        //mvp模式加载数据
        storeContentPresenter = new StoreContentPresenter(this);
        storeContentPresenter.loadStoreContentKorea();
        storeContentPresenter.loadStoreContentUsa();
        storeContentPresenter.loadStoreContentChiness();
        storeContentPresenter.loadStoreContentBeauty();

        loadHeadData();


    }


    private void setAdapter() {
        //广告轮播适配器
        storeHeadAdapter = new StoreAdvertisementAdapter(listHead, activity);
        storefragmentViewpager.setAdapter(storeHeadAdapter);

        storefragmentMgv.setAdapter(showAdapter);





    }


    private void loadHeadData() {
        //头标题解析
        Gson gson = new Gson();
        StoreHeadBean bean = gson.fromJson(UrlConfig.STORE_HEAD, new TypeToken<StoreHeadBean>() {
        }.getType());
        List<StoreHeadBean.DataBean.ItemsBean> items = bean.getData().getItems();
        //刷新适配器
        storeHeadAdapter.reloadData(items);

    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setListener();
        //开始轮播方法
        startAutoPlay();
    }

    private void setListener() {

        for (int i = 0; i < tabTitlie.length; i++) {

            storefragmentTablayout.addTab(storefragmentTablayout.newTab().setText(tabTitlie[i]),i);

        }
        storefragmentTablayout.setTabTextColors(Color.BLACK,Color.RED);
        storefragmentTablayout.getTabAt(0).select();
        storeContentPresenter.loadShowToday();
        storefragmentTablayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()){
                    case 0:
                        storeContentPresenter.loadShowToday();
                    break;
                    case 1:
                        storeContentPresenter.loadShowUp();
                    break;
                    case 2:
                        storeContentPresenter.loadShowDress();
                    break;
                    case 3:
                        storeContentPresenter.loadShowTrousers();
                    break;
                }


            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }


    private void startAutoPlay() {
        //广告页自动轮播
        final MyThread myThread = new MyThread();
        myThread.start();
        //设置手势监听
        storefragmentViewpager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    //按下的时候停止自动轮播
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        myThread.stopRun();
                        break;
                    //离开的时候开始轮播
                    case MotionEvent.ACTION_UP:
                        myThread.startRun();
                        break;
                }
                //必须返回false否则把事件拦截
                return false;
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //黄油刀解绑
        ButterKnife.unbind(this);
    }


    @Override
    public void onResponseKorea(StoreBean bean) {
        storefragmentMycontentviewKorea.pullData(bean);
        storefragmentMycontentviewKorea.setInter();

        storefragmentMycontentviewKorea.setOnClick(this);


    }

    @Override
    public void onFailureKorea(String s) {

    }

    @Override
    public void onResponseUsa(StoreBean bean) {
        storefragmentMycontentviewUsa.pullData(bean);
        storefragmentMycontentviewUsa.setInter();

        storefragmentMycontentviewUsa.setOnClick(this);


    }

    @Override
    public void onFailureUsa(String s) {

    }

    @Override
    public void onResponseChinese(StoreBean bean) {
        storefragmentMycontentviewChinese.pullData(bean);
        storefragmentMycontentviewChinese.setInter();

        storefragmentMycontentviewChinese.setOnClick(this);

    }

    @Override
    public void onFailureChinese(String s) {

    }

    @Override
    public void onResponseBeauty(StoreBean bean) {
        storefragmentMycontentviewBeauty.pullData(bean);
        storefragmentMycontentviewBeauty.setInter();
        storefragmentMycontentviewBeauty.setOnClick(this);
    }

    @Override
    public void onFailureBeauty(String s) {

    }

    @Override
    public void onResponseShow(ShowBean bean) {
        final List<ShowBean.DataBean.ItemsBean> items = bean.getData().getItems();
        showAdapter.reloadData(items);

        //show点击事件
        storefragmentMgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Log.i("jerry", "setViewPager:========= "+items.get(position).getComponent().getPicUrl());

            }
        });
    }

    @Override
    public void onFailureShow(String s) {

    }
//自定义view的三个点击事件
    @Override
    public void setViewPager(View view, StoreBean.DataBean.RegionPicturesBean bean) {
        Intent intent=new Intent(activity, DetailActivity.class);
        String id = bean.getComponent().getAction().getId();
        intent.putExtra("id",id);

        startActivity(intent);
    }

    @Override
    public void setRecyclerViewBrand(View view, StoreBean.DataBean.RegionBrandsBean bean) {
        Log.i("jerry", "setViewPager:========= "+bean.getComponent().getPicUrl());
    }

    @Override
    public void setRecyclerViewShow(View view, StoreBean.DataBean.RegionSkusBean bean) {
        Log.i("jerry", "setViewPager:========= "+bean.getComponent().getPicUrl());
    }


    class MyThread extends Thread {
        private boolean isflag;

        //根据状态判断停止轮播清空handler消息
        public void stopRun() {
            if (isflag) {
                isflag = false;
                handler.removeCallbacks(this);
            }
        }

        //根据状态判断开始轮播清空handler之前的消息
        public void startRun() {
            if (!isflag) {
                handler.removeCallbacks(this);
                isflag = true;
                handler.postDelayed(this, TIME);
            }

        }

        @Override
        public void run() {
            //发送空消息标记为0
            handler.sendEmptyMessage(0);
            //延迟发送消息递归调用自己的run方法达到轮播的效果
            handler.postDelayed(this, TIME);
        }
    }

}
